package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseApplyIn;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.PurchaseApply;
import com.wh.wisdomsite.xbox.st.entity.PurchaseDetail;
import com.wh.wisdomsite.xbox.st.service.IPurchaseApplyService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseDetailService;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;


/**
 * 请购申请审核controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.st
 * @date 2018年12月25日 15:39
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/purchaseApplyCheck")
public class PurchaseApplyCheckController {
    private static final Log logger = LogFactory.getLog(PurchaseApplyController.class);

    @Autowired
    private IPurchaseApplyService iPurchaseApplyService;

    @Autowired
    private IPurchaseDetailService iPurchaseDetailService;

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_purchaseApplyCheck_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/purchaseApplyCheck/checkList";
    }

    /**
     * 获取已上报数据集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_purchaseApplyCheck_find")
    @RequestMapping(value = "/checkList.do")
    public void checkList(HttpServletResponse response, PurchaseApplyIn in) {
        try{
            logger.info("加载已上报数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<PurchaseApply>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<PurchaseApply> ewPurchaseApply = new EntityWrapper<PurchaseApply>();
            ewPurchaseApply.setEntity(new PurchaseApply());
            if (StringUtils.isNotEmpty(in.getStartDate()) && StringUtils.isNotEmpty(in.getEndDate())) {
                ewPurchaseApply.between("pur.purDate", in.getStartDate(), in.getEndDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStartDate())) {
                ewPurchaseApply.between("pur.purDate", in.getStartDate(), in.getStartDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getEndDate())) {
                ewPurchaseApply.between("pur.purDate", in.getEndDate(), in.getEndDate() + " " + "23:59:59");
            }
            //只能看已上报的数据
            ewPurchaseApply.eq("pur.reportState", "2");
            //合同内的才存在对比数据
            ewPurchaseApply.eq("pur.purType", "1");
            if (StringUtils.isNotEmpty(in.getCheckState())) {
                ewPurchaseApply.eq("pur.checkState", in.getCheckState());
            }
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewPurchaseApply.like("p1.prName", in.getPrName());
            }
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewPurchaseApply.like("co.coNumber", in.getCoNumber());
            }
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewPurchaseApply.like("co.coName", in.getCoName());
            }
            //若不是超级管理员则根据用户权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewPurchaseApply = UserUtils.setEntityWrapper(ewPurchaseApply, "co1", "off1", "p1");
            }
            Page<Map<String, Object>> purchaseApplyPage = iPurchaseApplyService.getReportedPage(page, ewPurchaseApply);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (purchaseApplyPage.getRecords().size() > 0) {
                for (Map<String, Object> purchaseApply : purchaseApplyPage.getRecords()) {
                    JSONObject object = new JSONObject(purchaseApply);
                    object.put("purDate", DateTool.getFormatByMs(purchaseApply.get("purDate")));
                    if (purchaseApply.get("project") != null) {
                        object.put("project", new JSONObject(purchaseApply.get("project")));
                    }
                    if (purchaseApply.get("contract") != null) {
                        object.put("contract", new JSONObject(purchaseApply.get("contract")));
                    }
                    array.put(object);
                }
            }
            json.put("total", purchaseApplyPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载已上报数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载已上报数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转采购对比页面
     * @param request
     * @param purId
     * @return
     */
    @RequiresPermissions("rules:st_purchaseApplyCheck_contrast")
    @RequestMapping(value = "/toContrast.do")
    public String toContrast(HttpServletRequest request, String purId) {
        request.setAttribute("purId",purId);
        return "st/purchaseApplyCheck/contrastList";
    }

    /**
     * 获取采购对比数据
     * @param response
     * @param in
     * @return
     */
    @RequestMapping(value = "/getContrastList.do")
    public void getContrastList(HttpServletResponse response, PurchaseApplyIn in) {
        try{
            logger.info("加载采购对比数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<PurchaseDetail> page = new Page<PurchaseDetail>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<PurchaseDetail> ewPurchaseDetail = new EntityWrapper<PurchaseDetail>();
            ewPurchaseDetail.setEntity(new PurchaseDetail());
            ewPurchaseDetail.eq("purd.dataState", "1");
            if (StringUtils.isNotEmpty(in.getPurId())) {
                ewPurchaseDetail.eq("purd.purId", in.getPurId());
            }
            if(StringUtils.isNotEmpty(in.getMaterialName())){
                ewPurchaseDetail.like("ma.materialName",in.getMaterialName());
            }
            if(StringUtils.isNotEmpty(in.getPurdState())){
                ewPurchaseDetail.eq("purd.purdState",in.getPurdState());
            }
            ewPurchaseDetail.orderBy("purd.createDate", false);
            Page<Map<String, Object>> purchaseDetailPage = iPurchaseDetailService.getContrastPage(page, ewPurchaseDetail);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            int origIndex=1;
            if (purchaseDetailPage.getRecords().size() > 0) {
                for (Map<String, Object> purchaseDetail : purchaseDetailPage.getRecords()) {
                    JSONObject object = new JSONObject(purchaseDetail);
                    object.put("purdDate", DateTool.format((Date) purchaseDetail.get("purdDate"),"yyyy-MM-dd"));
                    object.put("origIndex",origIndex);
                    array.put(object);
                    origIndex++;
                }
            }
            json.put("total", purchaseDetailPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载采购对比数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载采购对比数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转合同剩余量
     * @param request
     * @param purId
     * @return
     */
    @RequiresPermissions("rules:st_purchaseApplyCheck_countLeft")
    @RequestMapping(value = "/toCountLeft.do")
    public String toCountLeft(HttpServletRequest request, String purId) {
        request.setAttribute("purId",purId);
        return "st/purchaseApplyCheck/countLeftList";
    }

}
